package com.Action;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;

import sun.misc.BASE64Decoder;
import transformFactory.OperateImage;

import com.Entity.CommentInfo;
import com.Entity.TopicInfo;
import com.Entity.UsersInfo;
import com.Entity.Page.Json;
import com.Service.CommentService;
import com.Service.TopicService;
import com.Service.UserService;

public class TopicAction extends BaseAction implements ServletResponseAware {

	private static final int MM = 0;

	private HttpServletResponse response;// response对象

	@Autowired
	private TopicService topicService;
	@Autowired
	private UserService userService;
	@Autowired
	private CommentService commentService;
	CommentInfo commentinfo = new CommentInfo();
	UsersInfo userinfo = new UsersInfo();
	TopicInfo topicinfo = new TopicInfo();
	private List<TopicInfo> topiclist = new ArrayList<TopicInfo>();
	private List<UsersInfo> userlist = new ArrayList<UsersInfo>();
	private List<CommentInfo> commentlist = new ArrayList<CommentInfo>();
	UsersInfo user = new UsersInfo();

	public List<UsersInfo> getUserlist() {
		return userlist;
	}

	public void setUserlist(List<UsersInfo> userlist) {
		this.userlist = userlist;
	}

	public UsersInfo getUsersinfo() {
		return userinfo;
	}

	public void setUsersinfo(UsersInfo userinfo) {
		this.userinfo = userinfo;
	}

	public TopicInfo getTopicInfo() {
		return topicinfo;
	}

	public void setTopicInfo(TopicInfo topicinfo) {
		this.topicinfo = topicinfo;
	}

	public List<TopicInfo> getTopiclist() {
		return topiclist;
	}

	public void setTopiclist(List<TopicInfo> topiclist) {
		this.topiclist = topiclist;
	}

	public CommentInfo getCommentInfo() {
		return commentinfo;
	}

	public void setCommentInfo(CommentInfo commentinfo) {
		this.commentinfo = commentinfo;
	}

	public List<CommentInfo> getCommentlist() {
		return commentlist;
	}

	public void setCommentlist(List<CommentInfo> commentlist) {
		this.commentlist = commentlist;
	}

	private int flag = 0;
	private String msg;

	// 发帖
	public void postTopic() throws ParseException, IOException {

		PrintWriter out = response.getWriter();

		StringBuffer jb = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = ServletActionContext.getRequest()
					.getReader();
			while ((line = reader.readLine()) != null)
				jb.append(line);
		} catch (Exception e) { /* report an error */
		}

		JSONObject jsonObject = JSONObject.fromObject(jb.toString());
		JSONObject returnjson = new JSONObject();

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8");

		String uploadPath;

		// familyname = new String(familyname.getBytes("ISO-8859-1"), "UTF-8");
		//
		// familyname = java.net.URLDecoder.decode(familyname,"UTF-8");

		int userid = jsonObject.getInt("userId");
		String content = jsonObject.getString("topicContent");

		topicinfo.setUserId(userid);
		if (null != content && !content.isEmpty()) {
			topicinfo.setTopicContent(content);
		}
		topicinfo.setPublicTime(new Timestamp(System.currentTimeMillis()));
		topicinfo.setCommentNum(0);
		topicinfo.setPraiseNum(0);

		// ByteArrayInputStream is = new
		// ByteArrayInputStream(jsonObject.get("fileData").toString().getBytes());
		BASE64Decoder decoder = new BASE64Decoder();

		if (null != jsonObject.get("fileData")) {
			String imageStr = jsonObject.get("fileData").toString();
			byte[] isbyte = decoder.decodeBuffer(imageStr);
			String path = ServletActionContext.getRequest().getContextPath();
			String basePath = ServletActionContext.getRequest().getScheme()
					+ "://" + ServletActionContext.getRequest().getServerName()
					+ ":" + ServletActionContext.getRequest().getServerPort()
					+ path + "/";

			uploadPath = ServletActionContext.getServletContext().getRealPath(
					"/upload");
			File dirFile = new File(uploadPath);
			// 判断当前文件夹（路径）是否存在，如果不存在则创建
			if (!dirFile.exists()) {
				// dirFile.mkdirs();
				dirFile.mkdir();
			}
			// 为文件重命名
			String realfileName = java.util.UUID.randomUUID().toString();
			realfileName += ".png";
			File toFile = new File(uploadPath, realfileName);

			// logger.info("图片存入本地的路径="+uploadPath+"\\"+fileName);
			BufferedOutputStream stream = null;
			try {
				FileOutputStream os = new FileOutputStream(toFile);
				stream = new BufferedOutputStream(os);
				stream.write(isbyte);
			} finally {
				stream.close();
			}

			String srcImagePath = uploadPath + "/" + realfileName;
			String toImagePath = uploadPath + "/" + realfileName;

			OperateImage operateimage = new OperateImage();
			operateimage.reduceImageEqualProportion(srcImagePath, toImagePath,
					1);
			String imageurl = basePath + "upload/" + realfileName;
			topicinfo.setImgUrl(imageurl);
			returnjson.put("imageurl", imageurl);
		}
		this.topicService.save(topicinfo);

		returnjson.put("success", true);
		returnjson.put("msg", "新建家庭组成功！");

		out.println(returnjson.toString());
		out.flush();
		out.close();
	}

	// 帖子列表
	public void getTopicList() throws UnsupportedEncodingException,
			ParseException {
		String page = ServletActionContext.getRequest()
				.getParameter("currpage");
		String rows = ServletActionContext.getRequest()
				.getParameter("pagesize");

		Json json = new Json();
		this.topiclist = topicService.getTpoicList(Integer.valueOf(page),
				Integer.valueOf(rows));
		List<Map<String, Object>> topic_list = new ArrayList<Map<String, Object>>();
		if (!topiclist.isEmpty()) {
			for (TopicInfo topic : topiclist) {
				Map<String, Object> map = new HashMap<String, Object>();
				user = this.userService.getById(topic.getUserId());

				map.put("topicId", topic.getTopicId());
				map.put("userId", topic.getUserId());
				map.put("userName", user.getUserName());
				map.put("userImg", user.getUserImg());
				map.put("topic", topic.getTopic());
				map.put("topicContent", topic.getTopicContent());
				map.put("imgUrl", topic.getImgUrl());
				map.put("publicTime", topic.getPublicTime());
				map.put("commentNum", topic.getCommentNum());
				map.put("praiseNum", topic.getPraiseNum());
				topic_list.add(map);
			}
			json.setObj(topic_list);
			json.setSuccess(true);
		} else {
			json.setMsg("获取失败！");
			json.setSuccess(false);
		}
		writeJson(json);
	}

	// 评论帖子
	public void commentTopic() throws UnsupportedEncodingException,
			ParseException {
		String topicid = ServletActionContext.getRequest().getParameter(
				"topicid");
		String userid = ServletActionContext.getRequest()
				.getParameter("userid");
		String comment = ServletActionContext.getRequest().getParameter(
				"comment");

		comment = new String(comment.getBytes("ISO-8859-1"), "UTF-8");

		comment = java.net.URLDecoder.decode(comment, "UTF-8");

		Json json = new Json();
		commentinfo.setTopicId(Integer.valueOf(topicid));
		commentinfo.setUserId(Integer.valueOf(userid));
		commentinfo.setComment(comment);
		commentinfo.setCommentTime(new Timestamp(System.currentTimeMillis()));
		topicinfo = this.topicService.getById(Integer.valueOf(topicid));
		commentinfo.setFloorNum(topicinfo.getCommentNum() + 2);
		topicinfo.setCommentNum(topicinfo.getCommentNum() + 1);

		commentService.save(commentinfo);
		topicService.save(topicinfo);
		json.setSuccess(true);
		writeJson(json);
	}

	// 点赞
	public void praiseTopic() throws UnsupportedEncodingException,
			ParseException {
		String topicid = ServletActionContext.getRequest().getParameter(
				"topicid");

		Json json = new Json();
		topicinfo = this.topicService.getById(Integer.valueOf(topicid));
		System.out.println(topicinfo);
		topicinfo.setPraiseNum(topicinfo.getPraiseNum() + 1);
		topicService.update(topicinfo);
		json.setSuccess(true);
		writeJson(json);
	}

	// 评论列表
	public void getCommentList() throws UnsupportedEncodingException,
			ParseException {
		String topicid = ServletActionContext.getRequest().getParameter(
				"topicid");
		String currpage = ServletActionContext.getRequest().getParameter(
				"currpage");
		String pagesize = ServletActionContext.getRequest().getParameter(
				"pagesize");
		int page = 1;
		int rows = 10;
		JSONObject json = new JSONObject();
		if (currpage != null && !currpage.equals("")) {
			page = Integer.valueOf(currpage);
		}
		if (pagesize != null && !pagesize.equals("")) {
			rows = Integer.valueOf(pagesize);
		}
		commentlist = this.commentService.findByTopicId(
				Integer.valueOf(topicid), page, rows);
		List<Map<String, String>> comment_list = new ArrayList<Map<String, String>>();

		if (!commentlist.isEmpty()) {
			for (CommentInfo commentinfo : commentlist) {
				Map<String, String> map = new HashMap<String, String>();
				user = this.userService.getById(commentinfo.getUserId());
				map.put("userName", user.getUserName());
				map.put("userImg", user.getUserImg());
				map.put("commentTime", commentinfo.getCommentTime().toString());
				map.put("comment", commentinfo.getComment());
				map.put("topicId", commentinfo.getTopicId().toString());
				map.put("commentId", commentinfo.getCommentId().toString());
				map.put("floorNum", commentinfo.getFloorNum().toString());
				comment_list.add(map);
			}
		}
		topicinfo = this.topicService.getById(Integer.valueOf(topicid));
		user = this.userService.getById(topicinfo.getUserId());
		Map<String, Object> map_topic = new HashMap<String, Object>();
		map_topic.put("topicId", topicinfo.getTopicId());
		map_topic.put("userId", topicinfo.getUserId());
		map_topic.put("topicContent", topicinfo.getTopicContent());
		if (null != topicinfo.getImgUrl() && "" != topicinfo.getImgUrl()) {
			map_topic.put("imgUrl", topicinfo.getImgUrl());
		}

		Timestamp date = topicinfo.getPublicTime();
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Object dateStr = sdf.format(date);
		map_topic.put("publicTime", dateStr);

		map_topic.put("commentNum", topicinfo.getCommentNum());
		map_topic.put("praiseNum", topicinfo.getPraiseNum());
		map_topic.put("userName", user.getUserName());
		if (null != user.getUserImg() && "" != user.getUserImg()) {
			map_topic.put("userImg", user.getUserImg());
		}

		json.put("topic", map_topic);
		if (!comment_list.isEmpty() || comment_list.size() > 0) {
			json.put("commentlist", comment_list);
		}
		Json returnjson = new Json();
		returnjson.setObj(json);
		returnjson.setSuccess(true);
		returnjson.setMsg("获取帖子详情成功！");
		try {
			writeJson(returnjson);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		// TODO Auto-generated method stub
		this.response = response;
	}
}
